package org.vdab.projects.tasks.shared.entities.impl;

import java.util.HashSet;
import java.util.Set;

import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import org.vdab.projects.tasks.client.util.MessageGuard;
import org.vdab.projects.tasks.shared.EntityManager;
import org.vdab.projects.tasks.shared.entities.ITaskBook;
import org.vdab.projects.tasks.shared.entities.ITaskList;

@PersistenceCapable
public class TaskBook extends BaseEntity<TaskBook> implements ITaskBook {

//	@SuppressWarnings("unused")
//	@PrimaryKey
//	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
//	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
//	protected String key;

	@SuppressWarnings("unused")
	@Persistent
	private String ownerID;

	// This Set of Keys is used to describe a many-to-many relationship
	// as described on
	// http://code.google.com/intl/nl-NL/appengine/docs/java/datastore/jdo/relationships.html#Unowned_Relationships
	@Persistent
	private Set<String> myTaskListsKey = new HashSet<String>();

	// The collection of TaskLists is not persisted because the are part of an
	// m-n relationschip, the Taskbook is not the owner of the relation.
	@NotPersistent
	private Set<ITaskList> myTaskLists;

	public TaskBook() {		
	}

	public void setOwnerId(String ownerId) {
		this.ownerID = ownerId;
	}

	// When modeling a many-to-many using Key values, be aware that it is the
	// app's responsibility to maintain both sides of the relationship
	@Override
	public void addTaskList(ITaskList taskList) throws Exception {
		if (!this.myTaskListsKey.contains(taskList.getKey())) {
			if(!hasLoadedTasklist()){ Load(); }
			this.myTaskLists.add(taskList);
			this.myTaskListsKey.add(taskList.getKey());
			taskList.addToTodobook(this);
		}
	}

	public TaskBook Load() throws Exception {
		if (this.myTaskLists == null) {
			this.myTaskLists = new HashSet<ITaskList>();			
			for (String key : myTaskListsKey) {
				myTaskLists.add(EntityManager.get().getTaskListByKey(key));
			}
		}
		return this;
	}

	@Override
	public Set<ITaskList> getTaskLists() throws Exception {		
		if(!hasLoadedTasklist()){ Load(); }
		return myTaskLists;
	}

	@Override
	public String getDisplayText() {		
		return "Taskbook (" + this.getKey() + ")";
	}

	public boolean hasLoadedTasklist() {		
		return this.myTaskLists!=null;
	}

	@Override
	public TaskBook save() throws Exception {
		EntityManager.get().saveTaskBook(this);
		MessageGuard.Log("Saving Taskbook");
		return this;
	}
}
